import { Component, Input, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { BoardVo } from 'src/app/model/board-vo';
import { ThreadsService } from 'src/app/services/threads.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { EntityPageResult } from 'src/app/model/entity-page-result';
import { ThreadsCollectStatsVo } from 'src/app/model/threads-collect-stats-vo';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-threads-infinite-scroll-list',
  templateUrl: './threads-infinite-scroll-list.component.html',
  styles: [``]
})
/**
 * 版块内容页中话题分页
 * @constructor
 */
export class ThreadsInfiniteScrollListComponent implements OnInit {
  @Input('board')
  public boardVo!: BoardVo;
  //当前分类|all:所有,tops:置顶,goods:精华,pic:图片,hots:火贴
  @Input('category')
  public threadsCategory!: string;
  //当前页码值
  @Input('page')
  public page!: number;
  //每页显示的数量
  @Input('pageSize')
  public pageSize!: number;
  public pageResult$!: Observable<EntityPageResult<ThreadsCollectStatsVo>>;
  //当前的URL,用以浏览历史:window.history.pushState
  private url: string = '#';

  //滚动到底部加载数据
  constructor(private location: Location, private activatedRoute: ActivatedRoute, private threadsService: ThreadsService) {
    this.activatedRoute.url.pipe(map(s => s.join('/'))).subscribe(res => {
      this.url = '/' + res;
    });
  }

  ngOnInit(): void {
    this.getDate();
  }

  //底部的点击加载更多,后期会替换为:自动加载
  public anymore(event: Event): void {
    this.page += 1;
    this.getDate();
    this.location.replaceState(this.url, 'c=' + this.threadsCategory + '&p=' + this.page + '&s=' + this.pageSize);
  }

  //加载指定页码的数据
  private getDate(): void {
    let qc:string = (this.threadsCategory && 'all'== this.threadsCategory)?'-':this.threadsCategory;
    this.pageResult$ = this.threadsService.getAll(this.boardVo.id, qc, this.page, this.pageSize);
  }
  
  //切换分类标签页
  public toggleTab(category: string): void{
    if(!category){
      return;
    }
    if(this.threadsCategory === category){
      return;
    }
    //重置分类
    this.threadsCategory = category;
    //重置页码
    this.page = 1;
    //重新拉取数据
    this.getDate();
    this.location.replaceState(this.url, 'c=' + this.threadsCategory + '&p=' + this.page + '&s=' + this.pageSize);
  }
}
